package com.qibiao.drawguess;

import java.lang.reflect.Array;
import java.util.ArrayList;

public class PictureData {
    public static final String LINE_TAG = "#";
    public static final String POINT_TAG = ",";

    private ArrayList<ArrayList<Float>> lines = new ArrayList<>();
    public PictureData(){

    }

    public void addPoint(float x, float y){
        ArrayList<Float> lastLine = lines.get(lines.size()-1);
        lastLine.add(x);
        lastLine.add(y);
    }

    public ArrayList<Float> newLine(float x, float y){
        ArrayList<Float> newLine = new ArrayList<>();
        newLine.add(x);
        newLine.add(y);

        lines.add(newLine);

        return newLine;
    }

    public int getLineCount(){
        return lines.size();
    }

    public ArrayList<Float> getLineById(int lineId){
        if(lineId<lines.size()){
            return lines.get(lineId);
        }

        return null;
    }

    public void clear(){
        lines.clear();
        lines = new ArrayList<>();
    }

    public String saveAsString(){
        String s = "";
        for(int i=0;i<lines.size();i++){
            ArrayList<Float> line=lines.get(i);
            String lineStr = "";
            for(int p=0;p<line.size();p++){
                float n = line.get(p);
                if(p>0){
                    lineStr += POINT_TAG;
                }
                lineStr += String.format("%f", n);
            }
            if(i>0){
                s += LINE_TAG;
            }
            s += lineStr;
        }

        return s;
    }

    public void readFromString(String pictureString){
        clear();

        if(pictureString == null || pictureString.length()<=0){
            return;
        }

        String[] linesStr = pictureString.split(LINE_TAG);
        for(int i=0;i<linesStr.length;i++){
            String lineStr = linesStr[i];
            String[] points = lineStr.split(POINT_TAG);
            for(int p=0;p<points.length;){
                String xStr = points[p];
                p++;
                String yStr = points[p];
                p++;
                float x = Float.parseFloat(xStr);
                float y = Float.parseFloat(yStr);
                if(p==2){
                    newLine(x,y);
                }else{
                    addPoint(x, y);
                }
            }
        }
    }
}
